<template>
  <div class="system-edit-dept-container" v-loading="fullscreenLoading" style="display:block;min-height: 500px">
    <el-steps :space="200" align-center>
      <el-step v-for="(t,index) in AllTable" :title="t.tableDispName"
               :status="index+1<active||V===10?'success':(index+1===active?'finish':'wait')"/>
    </el-steps>
    <div v-if="active===1||active===8">
      <vxe-form :data="active===1?MData:DData[DT.tableName][0]" :ref="el=>itemRefs[DT.tableName]=el"
                :rules="Rules[DT.tableName]" size="small">
        <vxe-form-item :visible="false" field="RecordID"></vxe-form-item>
        <vxe-form-item v-for="item in DT['Fields']" :key="item.fieldID" :span="item.allowFreeze>0?item.allowFreeze:6"
                       :title="item.fieldDispName" :visible="item.hidden===0" :field="item.fieldName"
                       :item-render="{events:{change:ValueChange}}">
          <template #default="{ data }">
            <div v-if="item.dataTypeID===1">
              <vxe-input v-model="data[item.fieldName]" v-show="item.componentID===0" :readonly="item.editable===0"
                         @blur="ValueChange(data,DT.Fields,item.fieldName)"></vxe-input>

              <div v-if="item.componentID>0 && item.componentType===1">
                <vxe-select v-if="item.checkboxRows!==1" :readonly="item.editable===0"
                            v-model="data[item.fieldName]" placeholder="下拉框" clearable
                            @change="ValueChange(data,DT.Fields,item.fieldName)" transfer>
                  <vxe-option v-for="(it,index) in Combo[item.fieldName]" :value="it.value" :label="it.label"
                              :key="index"></vxe-option>
                </vxe-select>
                <vxe-radio-group v-if="item.checkboxRows===1" :readonly="item.editable===0"
                                 v-model="data[item.fieldName]" @change="ValueChange(data,DT.Fields,item.fieldName)">
                  <vxe-radio v-for="(it,index) in Combo[item.fieldName]" :label="it.value"
                             :content="it.value"></vxe-radio>
                </vxe-radio-group>
              </div>
            </div>
            <vxe-input v-if="item.dataTypeID===2" v-model="data[item.fieldName]" :readonly="item.editable===0"
                       placeholder="请输入..." type="integer"
                       @blur="ValueChange(data,DT.Fields,item.fieldName)"></vxe-input>
            <vxe-input v-if="item.dataTypeID===3" v-model="data[item.fieldName]" :readonly="item.editable===0"
                       placeholder="请输入..." clearable type="float" :digits="item.fieldPrecision"
                       @blur="ValueChange(data,DT.Fields,item.fieldName)"></vxe-input>
            <vxe-input v-if="item.dataTypeID===4" v-model="data[item.fieldName]" :readonly="item.editable===0" transfer
                       placeholder="请输入..." clearable type="date"
                       @blur="ValueChange(data,DT.Fields,item.fieldName)"></vxe-input>


            <vxe-input v-if="item.dataTypeID===7" v-model="data[item.fieldName]" :readonly="item.editable===0"
                       placeholder="请输入..." clearable
                       @blur="ValueChange(data,DT.Fields,item.fieldName)"></vxe-input>
          </template>
        </vxe-form-item>
      </vxe-form>
    </div>
    <div v-if="active>1&&active<8">
      <vxe-toolbar size="mini" :buttons="toolbarButtons"
                   @button-click="(value)=>buttonsClick(value,DT.tableName,name)">
        <template #tools><span style="padding-right:30px">{{ DT.tableTitle }}</span></template>
      </vxe-toolbar>
      <vxe-table border keep-source show-overflow :id="DT.tableName" size="small"
                 :edit-rules="Rules[DT.tableName]" :column-config="{resizable: true}"
                 :checkbox-config="{highlight: true, range: true}" :data="DData[DT.tableName]"
                 :ref="el=>itemRefs[DT.tableName]=el"
                 :edit-config="{trigger: 'click', mode: 'cell',showIcon:false} "
                 :show-footer="ShowFooter[DT.tableName]"
                 :footer-method="footerMethod"
                 :row-config="{isCurrent: true, isHover: true}" :max-height="DT.length>1?'500':'5000'">
        <vxe-column type="seq" align="center" width="60"></vxe-column>
        <vxe-column type="checkbox" align="center" width="35"></vxe-column>
        <vxe-column v-for="(it,key) in Fields[DT.tableName]" :field="it.fieldName" show-overflow :key="key"
                    :title="it.fieldDispName" :formatter="formatData" :visible="it.hidden===0" :edit-render="{}">
          <template #edit="{ row }">
            <div v-if="it.dataTypeID===1">
              <vxe-input v-model="row[it.fieldName]" v-show="it.componentID===0" :readonly="it.editable===0"
                         @blur="ValueChange(row,DT.Fields,it.fieldName)"></vxe-input>
              <vxe-input v-if="it.componentID>0 && [3,6].includes(it.componentType)" :value="getextend(row,it)"
                         v-show="it.componentID>0" placeholder="请点击选择..." readonly class="my-search"
                         @suffix-click="showSource({DT:it ,value:row[it.fieldName],target:row,ref:DT.tableName})"
                         @blur="ValueChange(row,DT.Fields,it.fieldName)">
                <template #suffix>
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </template>
              </vxe-input>
              <vxe-select v-if="it.componentID>0 && it.componentType===1" :readonly="it.editable===0"
                          v-model="row[it.fieldName]" placeholder="下拉框" clearable
                          @blur="ValueChange(row,DT.Fields,it.fieldName)" transfer>
                <vxe-option v-for="(it,index) in Combo[it.fieldName]" :value="it.value" :label="it.label"
                            :key="index"></vxe-option>
              </vxe-select>
              <vxe-input v-if="it.componentID>0 && it.componentType===5" v-model="row[it.fieldName]"
                         :readonly="it.editable===0" placeholder="自动取得编号"
                         @suffix-click="getAutoCode( DT.Fields,row,it.fieldName)">
                <template #suffix><i class="el-icon-refresh-right"></i></template>
              </vxe-input>
            </div>
            <vxe-input v-if="it.dataTypeID===2" v-model="row[it.fieldName]" placeholder="请输入..."
                       :readonly="it.editable===0" type="integer"
                       @blur="ValueChange(row,DT.Fields,it.fieldName)"></vxe-input>
            <vxe-input v-if="it.dataTypeID===3" v-model="row[it.fieldName]" placeholder="请输入..."
                       :readonly="it.editable===0" type="float" :digits="it.fieldPrecision"
                       @blur="ValueChange(row,DT.Fields,it.fieldName)"></vxe-input>
            <vxe-input v-if="it.dataTypeID===4" v-model="row[it.fieldName]" placeholder="请输入..."
                       :readonly="it.editable===0" transfer clearable type="date"
                       @blur="ValueChange(row,DT.Fields,it.fieldName)"></vxe-input>
            <div v-if="[5,10].includes(it.dataTypeID)">
              <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
              <vxe-input :value="getextend(row,it)" placeholder="请选择图片" readonly class="my-search"
                         @suffix-click="showFiles({DT:it ,value:row[it.fieldName],target:row,ref:DT.tableName,multiple:false,fileType:'images'})"
                         @blur="ValueChange(row,DT.Fields,it.fieldName)">
                <template #suffix>
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </template>
              </vxe-input>
            </div>
            <div v-if="it.dataTypeID===6">
              <vxe-input v-model="row[it.fieldName]" v-show="false"></vxe-input>
              <vxe-input :value="getextend(row,it)" placeholder="请选择文件" readonly class="my-search"
                         @suffix-click="showFiles({DT:it ,value:row[it.fieldName],target:row,ref:DT.tableName,multiple:true,fileType:'files'})"
                         @blur="ValueChange(row,DT.Fields,it.fieldName)">
                <template #suffix>
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </template>
              </vxe-input>
            </div>
            <vxe-input v-if="it.dataTypeID===7" v-model="row[it.fieldName]" placeholder="请输入..."
                       :readonly="it.editable===0" clearable
                       @blur="ValueChange(row,DT.Fields,it.fieldName)"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div v-if="active===9">
      <el-form :model="wjForm" label-width="120px">
        <el-form-item>
          <div class="wjform">
            <div class="wj title1"> 一、供应商基本情况：</div>
            <div class="wj"> 1.完成并提交“新供应商提交资料清单”，见附录；</div>
            <div class="wj"> 2.贵公司主要产品：</div>
            <div class="wj"> （1）
              <el-input v-model="wjForm.item[0].name" size="small"/>
                             年产值：
              <el-input v-model="wjForm.item[0].ncz" size="small"/>
                             万人民币_，今年产值：
              <el-input v-model="wjForm.item[0].jncz" size="small"/>
                             每月平均产能
              <el-input v-model="wjForm.item[0].pjycn" size="small"/>
                             ；
            </div>
            <div class="wj"> （2）
              <el-input v-model="wjForm.item[1].name" size="small"/>
                             年产值：
              <el-input v-model="wjForm.item[1].ncz" size="small"/>
                             万人民币_，今年产值：
              <el-input v-model="wjForm.item[1].jncz" size="small"/>
                             每月平均产能
              <el-input v-model="wjForm.item[1].pjycn" size="small"/>
                             ；
            </div>
            <div class="wj"> （3）
              <el-input v-model="wjForm.item[2].name" size="small"/>
                             年产值：
              <el-input v-model="wjForm.item[2].ncz" size="small"/>
                             万人民币_，今年产值：
              <el-input v-model="wjForm.item[2].jncz" size="small"/>
                             每月平均产能
              <el-input v-model="wjForm.item[2].pjycn" size="small"/>
                             ；
            </div>
            <div class="wj"> 有无出口：
              <el-radio-group v-model="wjForm.ywck">
                <el-radio label="有" size="small">有</el-radio>
                <el-radio label="无" size="large">无</el-radio>
              </el-radio-group>
                             ，平均出口比例：
              <el-input v-model="wjForm.pjckbl" size="small"/>
                             ；
            </div>
            <div class="wj"> 3.贵公司去年产值：
              <el-input v-model="wjForm.qncz" size="small"/>
                             ，今年产值（目前为止）：
              <el-input v-model="wjForm.jncz" size="small"/>
                             ；
            </div>
            <div class="wj"> 主要客户：</div>
            <div class="wj"> （1）
              <el-input v-model="wjForm.kh[0].name" size="small"/>
                             ，占销售额：
              <el-input v-model="wjForm.kh[0].zb" size="small"/>
                             证明人
              <el-input v-model="wjForm.kh[0].zmr" size="small"/>
                             职务
              <el-input v-model="wjForm.kh[0].zw" size="small"/>
                             联系方式
              <el-input v-model="wjForm.kh[0].lxfs" size="small"/>
                             。
            </div>
            <div class="wj"> （2）
              <el-input v-model="wjForm.kh[1].name" size="small"/>
                             ，占销售额：
              <el-input v-model="wjForm.kh[1].zb" size="small"/>
                             证明人
              <el-input v-model="wjForm.kh[1].zmr" size="small"/>
                             职务
              <el-input v-model="wjForm.kh[1].zw" size="small"/>
                             联系方式
              <el-input v-model="wjForm.kh[1].lxfs" size="small"/>
                             。
            </div>
            <div class="wj"> （3）
              <el-input v-model="wjForm.kh[2].name" size="small"/>
                             ，占销售额：
              <el-input v-model="wjForm.kh[2].zb" size="small"/>
                             证明人
              <el-input v-model="wjForm.kh[2].zmr" size="small"/>
                             职务
              <el-input v-model="wjForm.kh[2].zw" size="small"/>
                             联系方式
              <el-input v-model="wjForm.kh[2].lxfs" size="small"/>
                             。
            </div>
            <div class="wj title1"> 二、商务能力</div>
            <div class="wj"> 1.贵公司是否有最小生产批量？
              <el-radio-group v-model="wjForm.sfjxpl">
                <el-radio label="是" size="small">是</el-radio>
                <el-radio label="否" size="large">否</el-radio>
              </el-radio-group>
                             ；若有，为多少：
              <el-input v-model="wjForm.zxpl" size="small"/>
                             个_；最小产品包装数量为：
              <el-input v-model="wjForm.zxbz" size="small"/>
                             ；
            </div>
            <div class="wj"> 2.贵公司是否有最小订购金额？
              <el-radio-group v-model="wjForm.sfzxje">
                <el-radio label="是" size="small">是</el-radio>
                <el-radio label="否" size="large">否</el-radio>
              </el-radio-group>
                             ；若有，为多少：
              <el-input v-model="wjForm.zxje" size="small"/>
                             ；可接受的订单范围是：
              <el-input v-model="wjForm.ddfw" size="small"/>
                             %。
            </div>
            <div class="wj"> 确认订单需要时间：
              <el-input v-model="wjForm.ddsj" size="small"/>
                             ；
            </div>
            <div class="wj"> 3.贵公司是否采用MRdiv或ERdiv等系统？
              <el-radio-group v-model="wjForm.sfME">
                <el-radio label="是" size="small">是</el-radio>
                <el-radio label="否" size="large">否</el-radio>
              </el-radio-group>
                             。
            </div>
            <div class="wj"> 4.贵公司（工厂）距离本公司
              <el-input v-model="wjForm.gsjl" size="small"/>
                             公里，主要交货方式为：
              <el-input v-model="wjForm.jffs" size="small"/>
                             （陆运）外运
              <el-input v-model="wjForm.wy" size="small"/>
                             ；
            </div>
            <div class="wj"> 5.贵公司能提供哪种发票：
              <el-input v-model="wjForm.fp" size="small"/>
                             ；
            </div>
            <div class="wj"> 6.贵公司要求的付款期限：
              <el-input v-model="wjForm.fkqx" size="small"/>
                             刚开始以现金提货，以后可以接受月结
              <el-input v-model="wjForm.yj" size="small"/>
                             ；
            </div>
            <div class="wj"> 7.贵公司能多快回复详细的询价单：
              <el-input v-model="wjForm.hf" size="small"/>
                             ；
            </div>
            <div class="wj"> 8.贵公司材料存在技术或质量隐患，要求来人至本现场解决，能提供支持吗？
              <el-checkbox v-model="wjForm.xczc" label="能" size="small"/>
                             ；若能，需要
              <el-input v-model="wjForm.jxbzsl" size="small"/>
                             小时到达现场。
            </div>
            <div class="wj"> 9.根据合同条款，若因贵公司质量、交期等因素影响我公司生产进度时，我方将采取罚款的方式来追偿由此所造成的损失，贵公司是否同意？
              <el-radio-group v-model="wjForm.sfpcfk">
                <el-radio label="同意" size="small">同意</el-radio>
                <el-radio label="不同意" size="large">不同意</el-radio>
              </el-radio-group>
                             。
            </div>
            <div class="wj"> 10.贵公司有提供详细的产品成本分析给客户吗？
              <el-checkbox v-model="wjForm.tgcbfx" label="有" size="small"/>
                             。
            </div>
            <div class="wj"> 11.贵公司有能力管理机密文件及产品吗？
              <el-checkbox v-model="wjForm.gljmwj" label="有" size="small"/>
                             。
            </div>
            <div class="wj"> 12.贵公司愿意同本公司签定机密泄露协议并且在保密的基础上生产产品吗？
              <el-input v-model="wjForm.jxbzsl" size="small"/>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!fullscreenLoading &&active<=10" style="padding-top: 50px;text-align: center">
      <el-button-group>
        <el-button type="primary" v-if="active>1" @click="active--">
          <el-icon class="el-icon--left">
            <ArrowLeft/>
          </el-icon>
          上一项目
        </el-button>
        <el-button type="primary" v-if="active<AllTable.length" @click="active++">下一项目
          <el-icon class="el-icon--right">
            <ArrowRight/>
          </el-icon>
        </el-button>
        <el-button type="success" v-if="V!==11" :disabled="V===10" @click="save">
          <el-icon class="el-icon--right">
            <Finished/>
          </el-icon>
          保存
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onBeforeMount, reactive, ref, toRefs, watch} from 'vue';
import XEUtils from "xe-utils"
import {getTemplate, UpDate} from "/@/api/linkoo/supplier/manager"
import templateEdit from "/@/views/linkoo/components/templateEdit.vue"
import {useRoute, useRouter} from "vue-router";
import {useStore} from '/@/store/index';
import {ElMessage, ElMessageBox} from "element-plus";

export default defineComponent({
  name: 'systemEditDept',
  components: {templateEdit},
  setup(props) {
    let router = useRouter()
    const route = useRoute()
    let state = reactive({
      Fields: {},
      DData: {},
      Template: {},
      MData: {},
      ShowFooter: {},
      store: useStore(),
      DetailTables: [],
      AllTable: [],
      Combo: {},
      V: 10,
      wjform: {},
      rules: {},
      refForm: {},
      itemRefs: {},
      active: 0,
      Rules: {},
      DT: {},
      FooterFields: {},
      fullscreenLoading: false,
      Add: true,
      TableData: [],
      toolbarButtons: [{code: 'add', name: '新增'}, {code: 'delete', name: '删除'}],
      MainPage: {pageNum: 1, pageSize: 10, totalResult: 0},
      load: true,
      selectTab: "",
      RecordID: 0,
      wjForm: {
        item: [{name: '', ncz: '', jncz: '', pjycn: ''}, {name: '', ncz: '', jncz: '', pjycn: ''}, {
          name: '',
          ncz: '',
          jncz: '',
          pjycn: ''
        }],
        kh: [{name: '', zb: '', zmr: '', zw: '', lxfs: ''}, {name: '', zb: '', zmr: '', zw: '', lxfs: ''}, {
          name: '',
          zb: '',
          zmr: '',
          zw: '',
          lxfs: ''
        }],
        pjckbl: '',
        qncz: '',
        jncz: '',
        zxpl: '',
        zxbz: '',
        zxje: '',
        ddfw: '',
        ddsj: '',
        gsjl: '',
        jffs: '',
        wy: '',
        fp: '',
        fkqx: '',
        yj: '',
        hf: '',
        jxbzsl: '',
        sfjxpl: '',
        sfzxje: '',
        xczc: '',
        tgcbfx: '',
        gljmwj: '',
        sfpcfk: '',
        ywck: '',
        sfME: ''
      }
    })
    let EditData = ref(null)
    let Active = ref<number>(0)
    onBeforeMount(async () => {
      if (state.load) {
        state.fullscreenLoading = true
        state.RecordID = state.store.state.userInfos.userInfos.deptId
        await getTemplate(state.RecordID).then((response) => {
          state.AllTable = response.data.info.tables
          state.DetailTables = response.data.info.tables.filter(item => item.tableType === 1)
          state.Rules = response.data.info.editRules || []
          state.Combo = response.data.info.combos
          state.Template = response.data.info.template
          XEUtils.arrayEach(response.data.info.tables, row => {
            state.ShowFooter[row.tableName] = false
            if (row['onSheet'] !== '') {
              state.FooterFields[row.tableName] = row['onSheet'].split(',')
              state.ShowFooter[row.tableName] = true
            }
            const F = XEUtils.orderBy(row.Fields, [['tableID', 'asc'], ['ob', 'asc'], ['fieldID', 'asc']])
            const T = {}
            XEUtils.arrayEach(F, (row1, index) => {
              T[index + 1 + ''] = row1
            })
            state.Fields[row.tableName] = T
          })
          console.log(state.ShowFooter)
          state.DData = response.data.data['ChildTables']
          if (!state.DData['LK101']) {
            state.DData['LK101'] = []
            const k = ['业务人员', '生产人员', '品管人员', '研发\\技术人员', '其它']
            XEUtils.arrayEach(k, (row, index) => {
              state.DData['LK101'].push({RecordID: state.RecordID, Seq: index, F397: row})
            })
          }
          state.MData = XEUtils.omit(response.data.data, ['ChildTables'])
          state.V = response.data.step + 1
          state.active = state.V === 10 ? 1 : state.V
          state.load = false
          state.fullscreenLoading = false

        })
      }
    })
    const sumNum = (list, field) => {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
      return count
    }
    const footerMethod = ({columns, data}) => {
      if (state.ShowFooter[state.DT.tableName]) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (state.FooterFields[state.DT.tableName].includes(column.property)) {
              return sumNum(data, column.property)
            }
            return null
          })
        ]
      }

    }
    // const updateFooterEvent = () => {
    //   const $table =state.itemRefs[state.DT.tableName]
    //   $table.updateFooter()
    // }

    const formatData = ({cellValue, row, column}) => {
      let extend = XEUtils.toStringJSON(row['Extend'])
      if (extend[column.field] === null || extend[column.field] === undefined) {
        extend[column.field] = cellValue ? cellValue : ''
      }
      return XEUtils.get(extend, column.field)
    }
    const save = async () => {
      let data = {}, err = false
      if (state.active === 1 || state.active === 8) {
        err = await state.itemRefs[state.DT.tableName].validate().catch(errMap => errMap)
        data = state.MData
        data['RecordID'] = state.RecordID
        if (state.active === 8) {
          data['Seq'] = 1
          data = [data]
        }

      } else if (state.active === 9) {
        data['RecordID'] = state.RecordID
        data['Seq'] = state.RecordID
        data['F457'] = state.wjForm
        data = [data]
      } else {
        err = await state.itemRefs[state.DT.tableName].validate().catch(errMap => errMap)
        data = state.itemRefs[state.DT.tableName].getTableData().fullData.map((row, index) => {
          row['RecordID'] = state.RecordID;
          row['Seq'] = index + 1;
          delete row['_X_ROW_KEY'];
          return row
        })
      }
      if (!err) {
        state.DData[state.DT.tableName] = data
        UpDate(state.DT.tableName, state.RecordID, data, state.active).then(res => {
          state.active++
        })
      }
    }
    const buttonsClick = async ({code, button, $event}, name, index) => {
      //  console.log(code, button,$event,"kkkk",name,state.itemRefs,index);
      state.selectTab = name
      switch (code) {
        case 'add': {
          const {row: fnewRow} = await state.itemRefs[name].insertAt({
            RecordID: state.RecordID,
            Seq: null,
            Extend: '{}'
          }, -1)
          await state.itemRefs[name].setEditCell(fnewRow, state.DT.Fields[0]['fieldName'])
          await state.itemRefs[name].setCurrentRow(fnewRow)
          break
        }
        case 'delete': {
          const Fieldrows = state.itemRefs[name].getCheckboxRecords()
          if (Fieldrows.length > 0) {
            ElMessageBox.confirm("您确定要删除该数据?", "警告", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              state.itemRefs[name].remove(Fieldrows)
            })
          } else {
            ElMessage({type: 'info', message: '选择数据后再删除!',})
          }
          break
        }

      }
    }
    const ValueChange = (data, fields, fieldName) => {
      state.itemRefs[state.DT.tableName].updateFooter()
      // let source = XEUtils.clone(data, true)
      // source = XEUtils.objectMap(source, item => item === null ? 0 : item)
      // fields.forEach(field => {
      //   if (field.componentType === 9 && field.componentFieldName !== '') {
      //     data[field.fieldName] = math.evaluate(field.componentFieldName, source).toFixed(field.fieldPrecision)
      //   }
      // })
    }

    watch(() => state.active, () => {
      if (state.active <= state.AllTable.length) {
        state.DT = state.AllTable[state.active - 1]
        if (state.DT.tableName === 'LK137') {
          state.wjForm = JSON.parse(state.DData[state.DT.tableName][0]['F457'])
        }
      }
    })
    return {
      EditData,
      Active,
      ValueChange,
      save,
      footerMethod,
      formatData,
      buttonsClick,
      ...toRefs(state)
    }
  }
});
</script>
<style>
.wjform {
  display: block;
}

.wjform .wj {
  font-size: 15px;
  line-height: 26px;
}

.wjform .title {
  font-size: 35px;
  text-align: center
}

.wjform .title1 {
  font-size: 22px
}

.wjform .el-input {
  width: 120px;
  font-size: 16px
}

.wj {
  font-size: 18px
}

.el-step__icon-inner {
  font-size: 15px !important;
  font-weight: 400 !important;
}
</style>
